package com.fuint.module.backendApi.controller;

import com.fuint.framework.web.BaseController;
import com.fuint.framework.web.ResponseObject;
import com.fuint.minio.minIOConst.BucketConst;
import com.fuint.minio.model.UploadResult;
import com.fuint.minio.service.MinIOService;
import com.fuint.utils.StringUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传管理控制类
 *
 * Created by FSQ
 * CopyRight https://www.fuint.cn
 */
@Api(tags="管理端-文件上传相关接口")
@RestController
@RequestMapping(value = "/backendApi/file")
public class BackendFileController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BackendFileController.class);

    @Autowired
    private Environment env;

    @Autowired
    private MinIOService minIOService;

    /**
     * 上传文件
     * oZO+dISatxSPMnUXh+4FVA==
     */
    @ApiOperation(value = "上传文件")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @CrossOrigin
    public ResponseObject upload( MultipartFile file) {

        if (file == null) {
            return getFailureResult(201, "图片不能为空" );
        }

        Map<String, String> resultMap = new HashMap<>();
        String originalFilename = file.getOriginalFilename();
        if (StringUtil.isEmpty(originalFilename)) {
            return getFailureResult(201, "上传出错啦");
        }

        String maxSizeStr = env.getProperty("images.upload.maxSize");

        // 默认限制2M
        float maxSize = 2;
        try {
            maxSize = Float.parseFloat(maxSizeStr);
        } catch (NumberFormatException e) {
            logger.error("图片允许的大小设置不正确", e);
        }
        if (file.getSize() > (maxSize * 1024 * 1024)) {
            return getFailureResult(201, "上传的图片不能大于" + maxSize + "MB");
        }

        String fileType = file.getContentType();
        if (fileType.indexOf("image") == -1) {
            return getFailureResult(201, "上传的图片格式有误");
        }

        String original = file.getOriginalFilename().toLowerCase();
        if (original.indexOf("jpg") == -1 && original.indexOf("jpeg") == -1 && original.indexOf("png") == -1 && original.indexOf("gif") == -1 && original.indexOf("bmp") == -1) {
            return getFailureResult(201, "上传的图片格式有误");
        }

        // 保存文件
        try {
            UploadResult result = minIOService.putObject(BucketConst.FUNINT_BUCKET,file.getInputStream(),  originalFilename);
            if (result.isSuccess()) { // 检查是否开启上传
                resultMap.put("status", "success");
                resultMap.put("domain", result.getGroup());
                resultMap.put("filePath", result.getInnerPath());
                resultMap.put("fileName", originalFilename);
                resultMap.put("state", "SUCCESS");
                resultMap.put("original", file.getOriginalFilename());
                resultMap.put("size", file.getSize()+"");
                resultMap.put("title", originalFilename);
                resultMap.put("type", file.getContentType());
                resultMap.put("url", result.getInnerPath());
            }
        } catch (Exception e) {
            return getFailureResult(201, "上传失败，请检查上传配置及权限");
        }

        return getSuccessResult(resultMap);
    }
}
